package com.ly.system.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.common.core.constant.BaseConstant;
import com.ly.common.core.utils.BaseUtils;
import com.ly.system.system.bean.entity.SysTenant;
import com.ly.system.system.bean.entity.SysUser;
import com.ly.system.mapper.SysTenantMapper;
import com.ly.system.service.ISysTenantService;
import com.ly.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 租户实现类
 *
 * @author jeecg
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    private final ISysUserService sysUserService;
    private final SysTenantMapper tenantMapper;

    @Override
    public R getId(String id) {
        // todo:权限处理
        SysTenant entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(SysTenant entity) {
        List<SysTenant> list = this.list(
                new LambdaQueryWrapper<SysTenant>()
                        .eq(ObjUtil.isNotNull(entity.getStatus()), SysTenant::getStatus, entity.getStatus())
                        .like(StrUtil.isNotBlank(entity.getName()), SysTenant::getName, entity.getName())
                        .orderByDesc(SysTenant::getCreateTime)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(SysTenant entity, Page<SysTenant> page) {
        IPage<SysTenant> pageList = this.page(
                page,
                new LambdaQueryWrapper<SysTenant>()
                        .eq(ObjUtil.isNotNull(entity.getStatus()), SysTenant::getStatus, entity.getStatus())
                        .like(StrUtil.isNotBlank(entity.getName()), SysTenant::getName, entity.getName())
                        .ge(ObjUtil.isNotEmpty(entity.getBeginDate()), SysTenant::getBeginDate, entity.getBeginDate())
                        .le(ObjUtil.isNotEmpty(entity.getEndDate()), SysTenant::getEndDate, entity.getEndDate())
                        .orderByDesc(SysTenant::getCreateTime)
        );
        return R.ok(pageList);
    }

    @Override
    public R add(SysTenant entity) {
        // 手动指定id
        Integer maxTenantId = tenantMapper.getMaxTenantId();
        entity.setId(maxTenantId + 1);
        entity.setHouseNumber(RandomUtil.randomStringUpper(6));
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(SysTenant entity) {
        if (StrUtil.isEmpty(entity.getHouseNumber())) {
            entity.setHouseNumber(RandomUtil.randomStringUpper(6));
        }
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<SysTenant> dto) {
        List<SysTenant> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public R getCurrentUserTenant() {
        SysUser user = sysUserService.getById(BaseUtils.getId());
        if(user==null && user.getTenantId()==null){
            return R.ok();
        }
        List<SysTenant> list = this.list(
                new LambdaQueryWrapper<SysTenant>()
                        .eq(SysTenant::getStatus, BaseConstant.STATUS_1)
                        .in(SysTenant::getId, user.getTenantId())
        );
        return R.ok(list);
    }

    @Override
    public R getRecyclePage(Page<SysTenant> page, SysTenant sysTenant) {
        List<SysTenant> list = tenantMapper.getRecyclePage(page, sysTenant);
        Page<SysTenant> pageList = page.setRecords(list);
        return R.ok(pageList);
    }

    @Override
    public R deleteLogicTenant(String ids) {
        Integer num = tenantMapper.deleteLogicTenant(StrUtil.split(ids, ","));
        return num > 0 ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R revertLogicTenant(String ids) {
        Integer num = tenantMapper.revertLogicTenant(StrUtil.split(ids, ","));
        return num > 0 ? R.ok(true, "还原成功") : R.fail("还原失败");
    }

    @Override
    public void changeOwenUserTenant(String userId, String tId) {
        // 旧拥有者退出后，需要将就拥有者的用户租户关系改成已离职------------
        SysUser user = sysUserService.getById(userId);
    }

}
